package controllers

import (
	"net/http"
	"strconv"
	"encoding/json"
)

type Account struct {
	UserName string
	Password string
	Amounts float64
}

var account = Account{UserName: "oldboy", Password:"123456", Amounts:10000}

func Base(w http.ResponseWriter, r *http.Request) (user Account, code int, err string)  {
	if r.Method != "POST" {
		err, code = "Method Not Allowed", http.StatusMethodNotAllowed
		return
	}
	userName, password := r.PostFormValue("user_name"), r.PostFormValue("password")
	money, _ := strconv.ParseFloat(r.PostFormValue("money"), 64)
	if userName == "" || password == "" {
		err, code = "fail parameter error", http.StatusBadRequest
		return
	}
	user = Account{UserName:userName, Password:password, Amounts:money}
	return
}

type ResponseJson struct {
	Code int `json:"code"`
	Data map[string]interface{} `json:"data"`
	Message string `json:"message"`
}

func SendOk(w http.ResponseWriter, res ResponseJson) {
	w.WriteHeader(http.StatusOK)
	bytes, _ := json.Marshal(res)
	w.Write(bytes)
}
//取款
func Withdraw(w http.ResponseWriter, r *http.Request) {
	user, code, err := Base(w, r)
	if err != "" {
		http.Error(w, err, code)
		return
	}
	if user.Amounts <= 0 || user.Amounts > account.Amounts {
		http.Error(w, "fail parameter error", http.StatusBadRequest)
		return
	}
	if user.UserName == account.UserName && user.Password == account.Password {
		account.Amounts -= user.Amounts
		res := ResponseJson{Code:200,Data:map[string]interface{}{
			"user":account.UserName,
			"amounts":account.Amounts,
		}, Message:"取款成功！"}
		SendOk(w, res)
	}
}
//存款
func Deposit(w http.ResponseWriter, r *http.Request) {
	user, code, err := Base(w, r)
	if err != "" {
		http.Error(w, err, code)
		return
	}
	if user.Amounts <= 0 {
		http.Error(w, "fail parameter error", http.StatusBadRequest)
		return
	}
	if user.UserName == account.UserName && user.Password == account.Password {
		account.Amounts += user.Amounts
		res := ResponseJson{Code:200, Data:map[string]interface{}{
			"user":account.UserName,
			"amounts":account.Amounts,
		}, Message:"存款成功！"}
		SendOk(w, res)
	}
}

//查询
func Query(w http.ResponseWriter, r * http.Request) {
	user, code, err := Base(w, r)
	if err != "" {
		http.Error(w, err, code)
		return
	}
	if user.UserName == account.UserName && user.Password == account.Password {
		res := ResponseJson{Code:200, Data: map[string]interface{}{
			"user":account.UserName,
			"amounts":account.Amounts,
		}, Message:"查询成功！"}
		SendOk(w, res)
	}
}